import { useGetFilterTypeName } from '@/components/Filters/Filter/hook';
import { FilterType } from 'common/utils/eq-filter/types';
import ScrollPageList, { PageListRef } from '@/components/ScrollPageList';
import { eqV1ControllerDelete, eqV1ControllerIndex } from '@/services/auto/eq';
import { ProTable } from '@ant-design/pro-components';
import { css } from '@emotion/react';
import { Link } from '@umijs/max';
import { Button, Card, Descriptions, message, Modal, Popconfirm, Space } from 'antd';
import { GetScrollPageParam } from 'common/interface';
import { getFilenameByKey } from 'common/utils/utils';
import { Fragment, useContext, useEffect, useRef, useState } from 'react';
import Add from './Add';
import Top10Modal from './Top10Modal';
import AddDiffBtn from '@/components/AddDiffBtn';
import SwitchOpen from './SwitchOpen';
import { Context } from '../../../mixer-huihifi/components/Provider';

export default () => {
  const hidContext = useContext(Context);

  const filterTypeNameMap = useGetFilterTypeName();

  const elementRef = useRef<HTMLDivElement>(null);

  const [searchParam, setSearchParam] = useState<{ keyword?: string }>();

  const scrollPageListRef = useRef<PageListRef<API.EQResult>>(null);

  const [list, setList] = useState<API.EQResult[]>();

  const [count, setCount] = useState<number>();

  const [loading, setLoading] = useState<boolean>();

  const [showPageScroll, setShowPageScroll] = useState<boolean>(false);

  const [top10SearchUuid, setTop10SearchUuid] = useState<string>();

  useEffect(() => {
    setShowPageScroll(true);
  }, []);

  return (
    <div
      ref={elementRef}
      className="h-full"
      css={css`
        .ant-pro-table,
        .ant-pro-card,
        .ant-pro-card-body {
          height: 100% !important;
        }

        .ant-table-wrapper {
          height: calc(100% - 64px);

          .ant-spin-nested-loading,
          .ant-spin-container,
          .ant-table,
          .ant-table-container {
            height: 100%;
          }

          .ant-table-body {
            height: calc(100% - 47px);
          }
        }
      `}
    >
      {hidContext && <Card className='mb-[16px]' title="我的耳机" extra={
        <Space>
          <Button type="primary" key="my-eq" ghost onClick={() => {
          }}>
            我的曲线
          </Button>
          <Button type="primary" key="disconnect" ghost onClick={() => {
            hidContext.disconnectDevice(hidContext.getDeviceId(hidContext.connectedDevices[0]));
          }}>
            断开
          </Button>
        </Space>
      }>
        <Descriptions items={[{
          label: 'Vendor ID',
          children: hidContext.connectedDevices[0].vendorId,
        }, {
          label: 'Product ID',
          children: hidContext.connectedDevices[0].productId,
        }]} />
      </Card>}
      <ProTable<API.EQResult>
        loading={loading}
        rowKey="uuid"
        scroll={{ y: '100%', scrollToFirstRowOnChange: true }}
        search={false}
        dataSource={list}
        pagination={false}
        toolbar={{
          settings: [],
          search: {
            onSearch: (value: string) => {
              setSearchParam({ keyword: value || undefined });
              scrollPageListRef.current?.scrollToTop();
            },
          },
          actions: [
            <span key="count">共计 {count ?? '-'} 条</span>,
            <Add
              key="add"
              reload={(uuid) => {
                scrollPageListRef.current?.refresh();
                setTop10SearchUuid(uuid);
              }}
            >
              <Button type="primary">添加AI调音定制</Button>
            </Add>,
          ],
        }}
        columns={[
          {
            title: '序号',
            key: 'index',
            width: 80,
            valueType: 'index',
          },
          {
            title: '耳机',
            dataIndex: 'currentName',
            render: (_, record) => {
              return (
                <Fragment>
                  {record.name}
                  {record.evaluationUuid && (
                    <Fragment>
                      <Link
                        className="ml-[8px]"
                        to={{
                          pathname: `/evaluation/${record.evaluationUuid}`,
                        }}
                        target="_blank"
                      >
                        实测数据
                      </Link>
                    </Fragment>
                  )}
                </Fragment>
              );
            },
          },

          {
            title: '采样点',
            dataIndex: 'filters',
            width: 350,
            render: (_, record) => {
              return record.filters?.length ? (
                <Space direction="vertical">
                  {record.filters.map((filter) => {
                    return `类型=${filterTypeNameMap[filter.filterType as FilterType]} 频率=${filter.frequency.toFixed()}Hz Gain=${filter.gain} Q=${filter.q}`;
                  })}
                </Space>
              ) : '-';
            },
          },

          {
            title: '试听音频文件',
            dataIndex: 'audioFiles',
            render: (_, record) => {
              return record.audioFiles?.length ? (
                <Space direction="vertical">
                  {record.audioFiles.map((file) => {
                    return getFilenameByKey(file);
                  })}
                </Space>
              ) : '-';
            },
          },

          {
            title: '添加/修改时间',
            dataIndex: 'updateTime',
            valueType: 'dateTime',
            width: 150,
          },
          {
            title: '是否公开',
            key: 'open',
            width: 100,
            render: (_, record) => {
              return <SwitchOpen data={record} />
            },
          },
          {
            align: 'center',
            title: '操作',
            key: 'option',
            valueType: 'option',
            width: 120,
            render: (_, record) => {
              return (
                <Space direction="vertical" size={0}>
                  <AddDiffBtn eqUuid={record.uuid} badgeProps={{
                    offset: [-15, 8]
                  }}>
                    <Button type="link">
                      添加对比
                    </Button>
                  </AddDiffBtn>

                  <Button
                    type="link"
                    onClick={() => {
                      setTop10SearchUuid(record.uuid);
                    }}
                  >
                    相似调音
                  </Button>

                  {hidContext && <Button
                    type="link"
                    onClick={() => {
                    }}
                  >
                    写入我的耳机
                  </Button>}

                  <Add
                    key="edit"
                    data={record}
                    reload={(uuid) => {
                      scrollPageListRef.current?.refresh();
                      setTop10SearchUuid(uuid);
                    }}
                  >
                    <Button type="link">编辑</Button>
                  </Add>

                  <Popconfirm
                    title="确定删除吗？"
                    onConfirm={() => {
                      eqV1ControllerDelete({ uuid: record.uuid }).then(() => {
                        message.success('删除成功');
                        scrollPageListRef.current?.refresh();
                      });
                    }}
                  >
                    <Button type="link">删除</Button>
                  </Popconfirm>
                </Space>
              );
            },
          },
        ]}
      />

      {showPageScroll && (
        <ScrollPageList<
          GetScrollPageParam<API.EqV1ControllerIndexParams>,
          API.EQResult
        >
          ref={scrollPageListRef}
          param={searchParam}
          service={eqV1ControllerIndex}
          order={{
            orderBy: 'createTime',
            direction: 'DESC',
          }}
          getScrollableTarget={() =>
            elementRef.current?.querySelector('.ant-table-body')!
          }
          onListChange={(l, c) => {
            setList(l);
            setCount(c);
          }}
          onLoadingChange={(l) => {
            setLoading(l);
          }}
        />
      )}

      {top10SearchUuid && (
        <Top10Modal
          uuid={top10SearchUuid}
          onCancel={() => {
            setTop10SearchUuid(undefined);
          }}
        ></Top10Modal>
      )}
    </div>
  );
};
